package eu.jpereira.trainings.designpatterns.creational.builder.json;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBody;
import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBodyBuilder;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SoldItem;

public class JSONReportBodyBuilder implements ReportBodyBuilder {

	private List<SoldItem> items;
	private boolean withItems;
	private String customerPhone;
	private String customerName;
	
	public JSONReportBodyBuilder()
	{
		withItems = false;
		items = new LinkedList<SoldItem>();
	}
	
	@Override
	public void withItems() {
		withItems = true;
	}

	@Override
	public void setCustomerName(String name) {
		customerName = name;
	}

	@Override
	public void newItem(String name, int quantity, double unitPrice) {
		items.add(new SoldItem(name, quantity, unitPrice));
	}

	@Override
	public void setCustomerPhone(String phone) {
		customerPhone = phone;
	}

	@Override
	public ReportBody getReportBody() {
		JSONReportBody reportBody = new JSONReportBody();
		
		reportBody.addContent("sale:{customer:{");
		reportBody.addContent("name:\"");
		reportBody.addContent(customerName);
		reportBody.addContent("\",phone:\"");
		reportBody.addContent(customerPhone);
		reportBody.addContent("\"}");
		
		if(withItems)
		{
			reportBody.addContent(",items:[");
			Iterator<SoldItem> it = items.iterator();
			while ( it.hasNext() )	
			{
				SoldItem item = it.next();
				reportBody.addContent("{name:\"");
				reportBody.addContent(item.getName());
				reportBody.addContent("\",quantity:");
				reportBody.addContent(String.valueOf(item.getQuantity()));
				reportBody.addContent(",price:");
				reportBody.addContent(String.valueOf(item.getUnitPrice()));
				reportBody.addContent("}");
				if ( it.hasNext() ) {
					reportBody.addContent(",");
				}
			}
			reportBody.addContent("]}");
		}
		
		return reportBody;
	}

}
